package com.etheart.framework.core.fulltextsearch;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.search.FullTextSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

@Repository("ebiz_IndexService")
public class IndexServiceImpl implements IndexService {
	private static int MAX_RESULT = 10000;
	private HibernateTemplate hibernateTemplate;

	@Autowired
	public IndexServiceImpl(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	public <T> void index(Class<T> clazz) {
		hibernateTemplate.flush();
		Session session = hibernateTemplate.getSessionFactory()
				.getCurrentSession();
		FullTextSession ftSession = org.hibernate.search.Search
				.getFullTextSession(session);
		Criteria criteria=ftSession.createCriteria(clazz);
		criteria.setMaxResults(MAX_RESULT);
		int start = 1;
		int resultNum =MAX_RESULT;
		while (resultNum >= MAX_RESULT) {
			criteria.setFirstResult(start);
			List<T> results = criteria.list();
			for (T result : results) {
				ftSession.index(result);
			}
			resultNum = results.size();
			start+=MAX_RESULT;
			ftSession.flushToIndexes();
		}
	}
	
	public <T> void purgeAll(Class<T> clazz) {
		hibernateTemplate.flush();
		Session session = hibernateTemplate.getSessionFactory()
				.getCurrentSession();
		FullTextSession ftSession = org.hibernate.search.Search
				.getFullTextSession(session);
		ftSession.purgeAll(clazz);
		ftSession.flushToIndexes();
	}

	public <T, I extends Serializable> void purge(Class<T> clazz, I id) {
		hibernateTemplate.flush();
		Session session = hibernateTemplate.getSessionFactory()
				.getCurrentSession();
		FullTextSession ftSession = org.hibernate.search.Search
				.getFullTextSession(session);
		ftSession.purge(clazz, id);
		ftSession.flushToIndexes();
	}



	public <T, I extends Serializable> void index(Class<T> entity, I id) {
		hibernateTemplate.flush();
		Session session = hibernateTemplate.getSessionFactory()
				.getCurrentSession();
		FullTextSession ftSession = org.hibernate.search.Search
				.getFullTextSession(session);
		Object attachedEntity = ftSession.get(entity, id);
		ftSession.index(attachedEntity);
		ftSession.flushToIndexes();
	}

	public <T, I extends Serializable> void delete(Class<T> entity, I id) {
		hibernateTemplate.flush();
		Session session = hibernateTemplate.getSessionFactory()
				.getCurrentSession();
		FullTextSession ftSession = org.hibernate.search.Search
				.getFullTextSession(session);
		T attachedEntity =  (T) ftSession.get(entity, id);
		ftSession.delete(attachedEntity);
		ftSession.flushToIndexes();
	}
}
